package cn.mavor.day0920;

public class NumberToChinese {
    // 定义中文数字
    private static final String[] CHINESE_NUMBERS = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
    // 定义中文单位
    private static final String[] CHINESE_UNITS = {"", "十", "百", "千"};
    // 定义大数单位
    private static final String[] BIG_UNITS = {"", "万", "亿"};

    public static void main(String[] args) {
        int number = 3011;
        System.out.println(convertToChinese(number));
    }

    public static String convertToChinese(int num) {
        if (num == 0) {
            return CHINESE_NUMBERS[0]; // 处理数字为0的情况
        }

        StringBuilder result = new StringBuilder();
        int bigUnitPos = 0; // 大数单位的位置
        boolean needZero = false; // 是否需要加“零”

        while (num > 0) {
            // 处理每四位数字
            int part = num % 10000;
            if (part > 0) {
                String partChinese = convertPartToChinese(part);
                if (needZero) {
                    result.insert(0, CHINESE_NUMBERS[0]);
                }
                result.insert(0, partChinese + BIG_UNITS[bigUnitPos]);
                needZero = part < 1000 && part > 0; // 需要加零的条件修正
            } else {
                needZero = result.length() > 0; // 遇到万、亿等单位之间有零的情况
            }

            num /= 10000;
            bigUnitPos++;
        }

        // 去除末尾多余的“零”
        String finalResult = result.toString();
        if (finalResult.endsWith(CHINESE_NUMBERS[0])) {
            finalResult = finalResult.substring(0, finalResult.length() - 1);
        }

        return finalResult;
    }

    // 处理每四位数
    private static String convertPartToChinese(int num) {
        StringBuilder partChinese = new StringBuilder();
        int unitPos = 0;
        boolean zeroFlag = false;

        while (num > 0) {
            int digit = num % 10;
            if (digit != 0) {
                if (zeroFlag) {
                    partChinese.insert(0, CHINESE_NUMBERS[0]);
                }
                partChinese.insert(0, CHINESE_NUMBERS[digit] + CHINESE_UNITS[unitPos]);
                zeroFlag = false;
            } else {
                zeroFlag = true;
            }

            num /= 10;
            unitPos++;
        }

        return partChinese.toString();
    }
}
